package 学生成绩查询管理系统.功能;



import javax.swing.*;
import java.awt.*;
import java.sql.*;

public class TeacherUpdate {
    private static final String URL = "jdbc:mysql://localhost:3306/studentmanager";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "123456";

    private static Connection connection;

    public TeacherUpdate() {
        initializeDatabase();
    }

    public void openUpdatePasswordDialog() {
        SwingUtilities.invokeLater(() -> {
            UpdatePasswordDialog updatePasswordDialog = new UpdatePasswordDialog(null, "修改密码", true);
            updatePasswordDialog.setLocationRelativeTo(null);
            updatePasswordDialog.setVisible(true);
        });
    }

    private void initializeDatabase() {
        try {
            connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "无法连接到数据库", "错误", JOptionPane.ERROR_MESSAGE);
            System.exit(1);
        }
    }

    private static class UpdatePasswordDialog extends JDialog {
        private JTextField accountTextField;
        private JTextField newPasswordTextField;

        public UpdatePasswordDialog(JFrame parent, String title, boolean modal) {
            super(parent, title, modal);
            setSize(400, 300);

            accountTextField = new JTextField(20);
            newPasswordTextField = new JTextField(20);

            JButton updateButton = new JButton("更新密码");
            updateButton.addActionListener(e -> updatePassword());

            JPanel panel = new JPanel(new GridLayout(7, 2, 10, 10));

            panel.add(new JLabel("账号:"));
            panel.add(accountTextField);
            panel.add(new JLabel("新密码:"));
            panel.add(newPasswordTextField);
            panel.add(new JLabel());
            panel.add(updateButton);

            add(panel);
        }

        private void updatePassword() {
            try {
                String account = accountTextField.getText();
                String newPassword = newPasswordTextField.getText();

                String updateQuery = "UPDATE teacheraccount SET password=? WHERE account=?";
                try (PreparedStatement preparedStatement = connection.prepareStatement(updateQuery)) {
                    preparedStatement.setString(1, newPassword);
                    preparedStatement.setString(2, account);
                    preparedStatement.executeUpdate();
                }

                JOptionPane.showMessageDialog(this, "密码更新成功", "成功", JOptionPane.INFORMATION_MESSAGE);
                dispose();
            } catch (SQLException e) {
                e.printStackTrace();
                JOptionPane.showMessageDialog(this, "更新密码失败", "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
}

